<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="deptSubmit">确定</el-button>
        <el-button @click="cancal">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    // 父向子传递的父亲id,用作儿子的pid
    parentId: {
      type: [String, Number],
      required: true
    },
    // 是否是编辑状态
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      // 判断是否为编辑状态
      if (this.isEdit) {
        // 是的话,将当前id的code删除,形成一个新数组
        codeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(`部门编码 ${value} 已存在`)) : callback()
    }
    const validName = (rule, value, callback) => {
      // 找到兄弟部门把名字全拿出来
      let nameList = this.originList
        .filter(item => item.pid === this.parentId)
        .map(item => item.name)
      // 编辑状态
      if (this.isEdit) {
        // 找到自己本身pid
        const obj = this.originList.find(item => item.id === this.parentId)
        const pid = obj.pid
        // 让namelist找到所有的pid相等的兄弟元素,并且把自己本身拿出去
        nameList = this.originList
          .filter(item => item.pid === pid && item
            .id !== this.parentId).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(`部门名称 ${value} 已存在`)) : callback()
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employees: [], // 部门负责人列表
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getEmployeeSimple()
    // 数据回填
    this.getDepartDetail()
  },
  methods: {
    // 添加新部门
    async addDepts() {
      // 1. 点击确定向后台发送请求,展开数据
      const res = await addDepartments({ ...this.form, pid: this.parentId })
      // 2.给用户提示信息
      this.$message.success(res.message)
      // 3.子向父传递更新列表事件
      this.$emit('upload-list')
      // 4.父组件接收到事件  ①关闭了显示框②重新渲染了列表数据
    },
    // 编辑部门资料
    async editDepts() {
      // 1. 点击确定向后台发送请求,展开数据
      const res = await updateDepartments(this.form)
      // 2.给用户提示信息
      this.$message.success(res.message)
      // 3.子向父传递更新列表事件
      this.$emit('upload-list')
      // 4.父组件接收到事件  ①关闭了显示框②重新渲染了列表数据
    },
    // 提交事件
    deptSubmit() {
      // 兜底验证
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.isEdit ? this.editDepts() : this.addDepts()
      })
    },
    // 取消事件
    cancal() {
      this.$emit('close')
    },
    // 这里封装获得员工列表方法,需要在created中调用方法才有数据
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      this.employees = res.data
    },
    // 封装编辑框数据回填
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        this.form = res.data
      }
    }
  }
}
</script>

<style lang="scss" scoped>
form.el-form {
  padding: 0 40px 0 20px;
}
.el-select {
  width: 100%;
}
</style>
